<template>
  <div>
    <el-row :gutter="15">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="100px" @submit.native.prevent>
        <template v-if="!loading && formOperates">
          <el-col :span="12">
            <el-form-item label="会员名称" prop="vipInfoId">
              <el-select v-model="dataForm.vipInfoId" placeholder="选择会员名称" :disabled="judgeWrite('vipInfoId')" @change="selectChange">
                <el-option v-for="(item,index) in vipInfoIdList" :key="index"
                  :label="item.vipName" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="会员等级" prop="vipLevelId">
              <el-select v-model="dataForm.vipLevelId" placeholder="选择会员等级" clearable :disabled="true">
                <el-option v-for="(item,index) in levelCodeList" :key="index" :label="item.levelName" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应交会费" prop="amount">
              <el-input v-model="dataForm.amount" placeholder="应交会费" :disabled="judgeWrite('amount')" type="number" :min="0" clearable>
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会费到期时间" prop="expireTime">
              <el-date-picker  v-model="dataForm.expireTime" placeholder="请选择时间" :disabled="judgeWrite('expireTime')" clearable  :style='{"width":"100%"}' type="date"  format="yyyy-MM-dd"  value-format="timestamp" ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="缴费方式" prop="paymentMethod">
              <el-select v-model="dataForm.paymentMethod" placeholder="选择缴费方式" :disabled="judgeWrite('paymentMethod')" clearable>
                <el-option v-for="(item,index) in paymentMethodList" :key="index"
                  :label="item.fullName" :value="item.sortCode">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="缴费时间" prop="paymentDate">
              <el-date-picker  v-model="dataForm.paymentDate" placeholder="请选择时间" :disabled="judgeWrite('paymentDate')" clearable  :style='{"width":"100%"}' type="datetime"  format="yyyy-MM-dd HH:mm:ss"  value-format="timestamp" ></el-date-picker>
            </el-form-item>
          </el-col>
        </template>
      </el-form>
    </el-row>
    <UserBox v-if="userBoxVisible" ref="userBox" @submit="submit" />
  </div>
</template>
<script>
import { vipInfoIdList, vipAmountInfo, addVipAmount, editVipAmount } from '@/api/asso/vip/vipAmount'
import { vipLevelList } from "@/api/asso/vip/vipInfo";
import { getVipGrade } from '@/api/asso/vip/vipLevel'
import { getDataInterfaceRes } from "@/api/systemData/dataInterface";
import { getDictionaryDataSelector } from "@/api/systemData/dictionary";
export default {
  components: {},
  props: [],
  data() {
    return {
      visible: false,
      loading: false,
      setting: {},
      eventType: "",
      userBoxVisible: false,
      currTableConf: {},
      addTableConf: {},
      tableRows: {},
      dataForm: {
        id: "",
        flowId: "",
        status: 1,
        freeapproveruserid: "",
        flowUrgent: 1,
        vipInfoId: undefined,
        amount: 0,
        expireTime: '',
        paymentMethod: '',
        paymentDate: '',
        vipLevelId: ''
      },
      tableRequiredData: {},
      dataRule: {
       vipInfoId: [
          { required: true, message: '会员名称不能为空', trigger: 'blur' },
        ],
        vipLevelId: [
          { required: true, message: '会员等级不能为空', trigger: 'change' },
        ],
        amount: [
          { required: true, message: '应交会费不能为空', trigger: 'blur' },
        ],
        expireTime: [
          { required: true, message: '会费到期时间不能为空', trigger: 'blur' },
        ],
        paymentMethod: [
          { required: true, message: '缴费方式不能为空', trigger: 'change' },
        ],
        paymentDate: [
          { required: true, message: '缴费时间不能为空', trigger: 'blur' },
        ]
      },
      paymentMethodList: [],
      levelCodeList: [],
      isEdit: false,
      keyword: "",
      parameterList: [],
      allParameterList: [],
      smsList: [],
      vipInfoIdList: []
    };
  },
  computed: {
    formOperates() {
      return this.setting.formOperates;
    },
  },
  watch: {},
  created() {},
  mounted() {},
  methods: {
    judgeShow(id) {
      if (!this.setting.formOperates || !this.setting.formOperates.length)
        return true;
      let arr = this.setting.formOperates.filter((o) => o.id === id) || [];
      if (!arr.length) return true;
      let item = arr[0];
      return item.read;
    },
    judgeWrite(id) {
      if (!this.setting.formOperates || !this.setting.formOperates.length)
        return false;
      let arr = this.setting.formOperates.filter((o) => o.id === id) || [];
      if (!arr.length) return true;
      let item = arr[0];
      return !item.write;
    },
    goBack() {
      this.$emit("refresh");
    },
    init(data) {
      this.dataForm.id = data.id || "";
      this.setting = data;
      this.visible = true;
      this.updateDataRule();
      this.getVipGrade()
      this.getPayType()
      this.getVipList()
      this.$nextTick(() => {
        // this.$refs["elForm"].resetFields();
        if (this.dataForm.id) {
          this.loading = true
          vipAmountInfo(this.dataForm.id).then(res => {
            this.loading = false
            this.dataForm = res.data
          }).catch(() => {
            this.loading = false
          })
        }
        this.$emit("setPageLoad");
      });
      this.$store.commit("generator/UPDATE_RELATION_DATA", {});
    },
    updateDataRule() {
      let newRules = {};
      for (let i = 0; i < this.setting.formOperates.length; i++) {
        const item = this.setting.formOperates[i];
        if (!item.id.includes("-")) {
          const newRulesItem = {
            required: item.required,
            message: item.name + "不能为空",
            trigger: item.trigger || "blur",
          };
          if (!this.dataRule.hasOwnProperty(item.id)) {
            if (item.required) this.$set(newRules, item.id, [newRulesItem]);
          } else {
            let withoutRequiredItem = true;
            for (let i = 0; i < this.dataRule[item.id].length; i++) {
              if (this.dataRule[item.id][i].hasOwnProperty("required")) {
                this.dataRule[item.id][i].required = item.required;
                withoutRequiredItem = false;
              }
            }
            if (withoutRequiredItem && item.required)
              this.dataRule[item.id].push(newRulesItem);
          }
        } else {
          let key = item.id.split("-")[0];
          let newId = item.id.split("-")[1];
          let newItem = {
            ...item,
            id: newId,
          };
          if (!this.tableRequiredData.hasOwnProperty(key)) {
            this.$set(this.tableRequiredData, key, [newItem]);
          } else {
            this.tableRequiredData[key].push(newItem);
          }
        }
      }
      this.dataRule = { ...this.dataRule, ...newRules };
    },
    exist() {
      let isOk = true;
      for (let key in this.tableRequiredData) {
        if (this.dataForm[key] && Array.isArray(this.dataForm[key])) {
          for (let i = 0; i < this.dataForm[key].length; i++) {
            let item = this.dataForm[key][i];
            inner: for (let id in item) {
              let arr =
                this.tableRequiredData[key].filter((o) => o.id === id) || [];
              if (!arr.length) continue inner;
              if (arr[0].required) {
                let msg = `${arr[0].name}不能为空`;
                let boo = true;
                if (arr[0].dataType === "array") {
                  boo = !this.jnpf.isEmptyArray(item[id]);
                } else {
                  boo = !this.jnpf.isEmpty(item[id]);
                }
                if (!boo) {
                  this.$message({
                    message: msg,
                    type: "error",
                    duration: 1000,
                  });
                  isOk = false;
                  break;
                }
              }
            }
          }
        }
      }
      return isOk;
    },
    judgeRequired(id) {
      if (!this.formOperates || !this.formOperates.length) return false;
      let arr = this.formOperates.filter((o) => o.id === id) || [];
      if (!arr.length) return false;
      let item = arr[0];
      return item.required;
    },
    // 表单提交
    dataFormSubmit(eventType, flowUrgent) {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if(this.dataForm.amount <= 0){
            this.$message.error('会费金额请输入正数')
            return
          }
          if (this.exist && !this.exist()) return;
          if (eventType === "audit" || eventType === "reject") {
            this.$emit("eventReceiver", this.dataForm, eventType);
            return;
          }
          this.dataForm.status = eventType === "submit" ? 0 : 1;
          this.dataForm.flowId = this.setting.flowId;
          this.dataForm.flowUrgent = flowUrgent;
          this.eventType = eventType;
          if (this.eventType === "submit") {
            this.$confirm("您确定要提交当前流程吗, 是否继续?", "提示", {
              type: "warning",
            })
              .then(() => {
                this.request();
              })
              .catch(() => {});
          } else {
            this.request();
          }
        }
      });
    },
    request() {
      if (!!this.dataForm.id) {
            editVipAmount(this.dataForm.id, this.dataForm).then((res) => {
              this.$message({
                message: res.msg,
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.btnLoading = false
                  this.$emit('close', true)
                }
              })
            }).catch(() => { this.btnLoading = false })
          } else {
            addVipAmount(this.dataForm).then((res) => {
              this.$message({
                message: res.msg,
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.btnLoading = false
                  this.$emit('close', true)
                }
              })
            }).catch(() => { this.btnLoading = false })
          }
    },
    openSelectDialog(key) {
      this.currTableConf = this.addTableConf[key];
      this.currVmodel = key;
      this.selectDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.selectDialog.init();
      });
    },
    addForSelect(data) {
      for (let i = 0; i < data.length; i++) {
        let item = { ...this.tableRows[this.currVmodel], ...data[i] };
        this.dataForm[this.currVmodel].push(item);
      }
    },
    dataList() {
      var _data = JSON.parse(JSON.stringify(this.dataForm));

      return _data;
    },
    dataInfo(dataAll) {
      let _dataAll = dataAll;
      this.dataForm = _dataAll;
    },
    // 获取会员等级列表数据
    getVipGrade() {
      vipLevelList().then((res) => {
        if (res.code == 200) {
          this.levelCodeList = res.data.list;
        }
      });
    },
    // 获取会员列表
    getVipList(){
      vipInfoIdList().then((res) => {
        if (res.code == 200) {
          this.vipInfoIdList = res.data.list;
        }
      });
    },
    // 获取会员缴费方式
    getPayType(){
      getVipGrade('367299187424887877').then(res => {
        if(res.code == 200){
          this.paymentMethodList = res.data.list
        }
      })
    },
    // 选择会员带出会员等级
    selectChange(e){
      this.dataForm.vipLevelId = ''
      try{
        this.vipInfoIdList.forEach((item) => {
          if(item.id == e){
            this.dataForm.vipLevelId = item.vipLevelId
            throw Error();
          }
        })
      }catch(e){
        console.log(e)
      }
    }
  },
};
</script>
